package com.guochenglang.www.util.jwts;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.Properties;


/**
 * @author GuoChenglang
 */
public class JwtUtils {
    /**
     * 密匙
     */
    private static String sign;
    /**
     * 令牌有效时间
     */
    private static Integer date;

    static {
        Properties prop = new Properties();
        //读取properties文件
        InputStream inputStream = com.guochenglang.www.util.connect.Config.class.getClassLoader().getResourceAsStream("JwtProperties.properties");
        try {
            prop.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //对初始值进行赋值
        sign = prop.getProperty("sign");
        date = Integer.valueOf(prop.getProperty("during"));
    }


    /**
     * 生成jwt令牌
     *
     * @param data 数据map集合
     * @return jwt令牌
     */
    public static String getJwt(Map<String, Object> data) {
        String jwt = Jwts.builder()
                .setClaims(data)
                .signWith(SignatureAlgorithm.HS256, sign)
                .setExpiration(new Date(System.currentTimeMillis() + date)).compact();

        return jwt;
    }

    /**
     * 实例jwt令牌
     *
     * @param jwt jwt令牌
     * @return 实例化对象
     */
    public static Claims parseJwt(String jwt) {
        Claims obj = Jwts.parser()
                .setSigningKey(sign)
                .parseClaimsJws(jwt)
                .getBody();
        return obj;

    }

}
